package com.wxpay.springbootwxpay.controller;


import com.wxpay.springbootwxpay.constant.WXConstEnum;
import com.wxpay.springbootwxpay.service.WxPayService;
import com.wxpay.springbootwxpay.wxpayUtils.WxPayUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Api(value = "微信支付接口",tags = "微信支付接口")
@RestController
@RequestMapping(value = "/payment/")
@Slf4j
public class PaymentController {

    @Resource
    private WxPayService wxPayService;

    /**
     * TODO 自写微信统一下单接口
     * 购买的价格是固定值18.00元
     * @推荐使用 扩展性强
     * @param openId
     * @return
     */
    @ApiOperation("微信预支付2（推荐）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId",value = "用户openId")
    })
    @PostMapping(value = {"toWxPay"})
    public ResponseEntity ToWxPay(@RequestParam String openId) throws Exception {
        if(StringUtils.isEmpty(openId)){
            return ResponseEntity.ok("openId为空！");
        }
        /**
         * 这里是直接进行统一下单
         */
        //money 也可由前端传递不需要 后面就不要需要double转String
        Map<String, String> resMap = wxPayService.xcxPayment("sasas",18,openId);
        if("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))){
            //统一下单成功
            resMap.remove("returnCode");
            resMap.remove("returnMsg");
            log.info("【小程序支付服务】支付下单成功！");
            return ResponseEntity.ok(resMap);
        }else{
            log.info("【小程序支付服务】支付下单失败！原因:"+resMap.get("returnMsg"));
            return ResponseEntity.ok(resMap.get("returnMsg"));
        }
        /**         这里是查了订单状态 获取订单编号再进行统一下单
        //通过openId查询用户
        Condition usercondition = new Condition(User.class);
        usercondition.createCriteria().andEqualTo("wxId",openId);
        User user=userService.findByCondition(usercondition,null).get(0);
        通过用户ID查询蓝牙订单
        Condition bizBluetoothOrderC=new Condition(BizBluetoothOrder.class);
        bizBluetoothOrderC.createCriteria().andEqualTo("uId",user.getId());
        List<BizBluetoothOrder> bizBluetoothOrderlist = bizBluetoothOrderService.findByCondition(bizBluetoothOrderC,null);
        if(bizBluetoothOrderlist.isEmpty()){
            return failResult("订单不存在！");
        }
        BizBluetoothOrder bizBluetoothOrder = bizBluetoothOrderlist.get(0);
        if(bizBluetoothOrder.getStatus() != 0){//0未支付
            //释放三目   可添加 （未支付）（待付款）（已支付）
            //String msg = bizBluetoothOrder.getStatus() >1 ? "此订单已支付！":"订单未提交，请确认！";
            return failResult("此订单已支付！");
        }else {
            try {
                //money 也可由前端传递不需要 后面就不要需要double转String
                Map<String, String> resMap = wxPayService.xcxPayment(bizBluetoothOrder.getOrderSn(),18,openId);
                if("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))){
                    //统一下单成功
                    resMap.remove("returnCode");
                    resMap.remove("returnMsg");
                    log.info("【小程序支付服务】支付下单成功！");
                    return ResponseEntity.ok(resMap);
                }else{
                    log.info("【小程序支付服务】支付下单失败！原因:"+resMap.get("returnMsg"));
                    return ResponseEntity.ok(resMap.get("returnMsg"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
         */
    }

    @ApiOperation("生成随机数")
    @GetMapping("makeUUID")
    public ResponseEntity makeUUID(){
        return ResponseEntity.ok(WxPayUtils.makeUUID(32));
    }

    /**
     * TODO 微信支付回调Api√
     * @param request
     * @param response
     * @throws Exception
     */
    @ApiOperation("微信支付回调Api")
    @ApiImplicitParam(name = "request",value = "微信回调")
    @GetMapping(value="xcxNotify")
    public ResponseEntity xcxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream =  request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
        }
        outputStream.close();
        inputStream.close();
        Map map = WxPayUtils.xmlToMap(new String(outputStream.toByteArray(),"utf-8"));
        log.info("【小程序支付回调】 回调数据： \n"+map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if (WXConstEnum.SUCCESS.equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if(WXConstEnum.SUCCESS.equals(returnmsg)){
                //更新数据 商户订单号< 0
                int result = wxPayService.xcxNotify(map);
                if(result > 0){
                    //写自己的业务逻辑  （更改订单在数据库的支付状态）待完成...



                    //支付成功
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                            + "<return_msg><![CDATA[OK]]></return_msg>"+"</xml>";
                }
            }else{
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                log.info("支付失败:"+resXml);
            }
        }else{
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            log.info("【订单支付失败】");
        }
        log.info("【小程序支付回调响应】 响应内容：\n"+resXml);
        //写到前端
        response.getWriter().print(resXml);
        return ResponseEntity.ok(resXml);
    }

}
